<template>
  <div class="system-role">
    <div class="table-container">
      <table-header
        v-model:columns="columns"
        table-id="systemRole"
        :buttons="['refresh', 'add', 'colSetting']"
        role-prefix="system:role"
        @refresh="getRoleList"
        @create="handleCreate"
      />
      <table-base
        :loading="loading"
        :total="total"
        :table-data="roleList"
        :columns="columns"
        @handlePageChange="handlePageChange"
      >
        <template #create-time="scope">
          {{ formatDateTime(scope.row.createTime) }}
        </template>
        <template #option="scope">
          <div v-if="scope.row.roleCode !== 'SuperAdmin'">
            <el-button
              v-btn-permission="'system:role:edit'"
              type="primary"
              text
              class="btn-text btn-text-primary"
              @click="handleEdit(scope.row.id)"
            >
              编辑
            </el-button>
            <el-button
              v-btn-permission="'system:role:delete'"
              type="danger"
              text
              class="btn-text btn-text-danger"
              @click="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </div>
        </template>
      </table-base>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, reactive } from "vue"
import { getRoleById, getRoleByPage } from "@/api/role"
import { showErrorToast } from "@/utils/toast"
import { formatDateTime } from "@/utils/format"
import TableHeader from "@/components/base/TableHeader.vue"
import TableBase from "@/components/base/TableBase.vue"
import { columns } from "./config/content.config"

const loading = ref(false)
const roleList = ref<RoleResponse[]>([])
const total = ref(0)
const searchParams = reactive<RoleQueryRequest>({
  pageIndex: 1,
  pageSize: 10
})

const handlePageChange = (pageIndex: number, pageSize: number) => {
  searchParams.pageIndex = pageIndex
  searchParams.pageSize = pageSize
  getRoleList()
}

const handleCreate = () => {}

const handleEdit = async (id: number) => {
  if (!id) return

  try {
    const res = await getRoleById({ id })
    if (res.data) {
      console.log("🚀 ~ handleEdit ~ res.data:", res.data)
    }
  } catch (error: any) {
    showErrorToast(error.message)
  }
}

const handleDelete = (id: number) => {
  console.log("🚀 ~ handleDelete ~ id:", id)
}

onMounted(() => {
  getRoleList()
})

async function getRoleList() {
  loading.value = true
  try {
    const res = await getRoleByPage(searchParams)
    if (res.data) {
      roleList.value = res.data.list ?? []
      total.value = res.data.totalCount ?? 0
    }
  } catch (error: any) {
    showErrorToast(error.message)
  } finally {
    loading.value = false
  }
}
</script>

<style lang="scss" scoped></style>
